package com.qys.livesMall.quartz.controller.sys;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.quartz.domain.SysJob;
import com.qys.livesMall.quartz.service.ISysJobService;
import com.qys.livesMall.quartz.util.Constants;
import com.qys.livesMall.quartz.util.CronUtils;
import com.qys.livesMall.quartz.util.ScheduleUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 调度任务信息操作处理
 *
 * @author wanglei
 */
@RestController
@Tag(name = "后台管理-定时任务")
@RequestMapping("/sys/monitor/job")
public class SysJobController {


    @Autowired
    private ISysJobService jobService;

    /**
     * 查询定时任务列表
     */
    @PostMapping("/list")
    @Operation(summary = "查询定时任务列表")
    public R<Page<SysJob>> list(@RequestBody SysJob sysJob) {
        Page<SysJob> page=new Page<>(sysJob.getPageNum(),sysJob.getPageSize());
        List<SysJob> list = jobService.selectJobList(sysJob);
        page.setRecords(list);
        return R.ok(page);
    }

    /**
     * 获取定时任务详细信息
     */
    @Operation(summary = "获取定时任务详细信息")
    @GetMapping(value = "/{jobId}")
    public R<SysJob> getInfo(@PathVariable("jobId") Long jobId) {
        return R.ok(jobService.selectJobById(jobId));
    }

    /**
     * 新增定时任务
     */
    @PostMapping
    @Operation(summary = "新增定时任务")
    public R<?> add(@RequestBody SysJob job) throws SchedulerException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return R.fail("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return R.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return R.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return R.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return R.fail("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return R.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        job.setCreateBy(SecurityUtils.getUsername());
        return jobService.insertJob(job) > 0 ? R.ok() : R.fail();
    }

    /**
     * 修改定时任务
     */
    @PutMapping
    @Operation(summary = "修改定时任务")
    public R<?> edit(@RequestBody SysJob job) throws SchedulerException{
        if (!CronUtils.isValid(job.getCronExpression())) {
            return R.fail("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return R.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return R.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return R.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return R.fail("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return R.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        job.setUpdateBy(SecurityUtils.getUsername());
        return jobService.updateJob(job) > 0 ? R.ok() : R.fail();
    }

    /**
     */
    @Operation(summary = "修改状态")
    @PutMapping("/changeStatus")
    public R<?> changeStatus(@RequestBody SysJob job) throws SchedulerException {
        SysJob newJob = jobService.selectJobById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return jobService.changeStatus(newJob) > 0 ? R.ok() : R.fail();
    }

    /**
     * 定时任务立即执行一次
     */
    @Operation(summary = "定时任务立即执行一次")
    @PutMapping("/run")
    public R<?> run(@RequestBody SysJob job) throws SchedulerException {
        boolean result = jobService.run(job);
        return result ? R.ok() : R.fail("任务不存在或已过期！");
    }

    /**
     * 删除定时任务
     */
    @Operation(summary = "删除定时任务")
    @DeleteMapping("/{jobIds}")
    public R<?> remove(@PathVariable Long[] jobIds) throws SchedulerException{
        jobService.deleteJobByIds(jobIds);
        return R.ok();
    }
}
